<template>
  <div class="insp">
    <div class="insp-header">
      <div class="flexBetween">
        <div class="flex insp-header-left">
          <el-input placeholder="请输入养护计划名称" clearable v-model="curingPlanName" size="small" style="width: 150px;"
            class="mRight10">
          </el-input>
          <el-button class="btn" type="primary" size="small" @click="queryForPage(1)">查询</el-button>
        </div>
        <div>
          <el-button size="small" type="primary" icon="el-icon-plus" @click="handleAdd">新建养护计划</el-button>
        </div>
      </div>
    </div>

    <div class="insp-content">
      <div class="insp-table">
        <el-table :data="tableData" stripe :header-cell-style="{
          background: '#8595B9',
          color: '#fff',
          height: '44px',
        }" max-height="660px">
          <el-table-column prop="name" label="计划名称" show-overflow-tooltip></el-table-column>
          <el-table-column prop="maintenanceObject" label="养护对象" show-overflow-tooltip></el-table-column>
          <el-table-column prop="maintenanceDescribe" label="养护内容" show-overflow-tooltip></el-table-column>
          <el-table-column prop="bridgeName" label="养护桥梁" show-overflow-tooltip></el-table-column>
          <el-table-column prop="cycle" label="周期" show-overflow-tooltip></el-table-column>
          <el-table-column prop="intervalTime" label="执行时间区间" show-overflow-tooltip></el-table-column>
          <el-table-column prop="validTime" label="有效时间区间" show-overflow-tooltip></el-table-column>
          <el-table-column prop="type" label="检查类型" show-overflow-tooltip>
            <template slot-scope="scope">
              <label :class="['insp-table-label', inspTypeClass(scope.row.type)]">
                {{ inspTypeText(scope.row.type) }}
              </label>
            </template>
          </el-table-column>
          <el-table-column prop="maintenanceNormStr" label="创建依据" show-overflow-tooltip></el-table-column>
          <el-table-column prop="createUserName" label="创建人" show-overflow-tooltip></el-table-column>
          <el-table-column prop="createTime" label="创建时间" show-overflow-tooltip></el-table-column>
          <el-table-column property="state" label="状态" show-overflow-tooltip>
            <template slot-scope="scope">
              <label :class="['insp-table-label', statusClass(scope.row.state)]">{{statusText(scope.row.state)}}</label>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-tooltip content=" 修改">
                <el-button type="text" icon="el-icon-edit-outline" @click="handleEdit(scope.row.id)">
                </el-button>
              </el-tooltip>
              <el-tooltip content="删除">
                <el-button type="text" icon="el-icon-delete" style="color: red !important;"
                  @click="handelDelete(scope.row.id)">
                </el-button>
              </el-tooltip>
              <el-tooltip :content="scope.row.switch?`关闭`:`启用`">
                <el-switch v-model="scope.row.switch" @change="handleChangeStatus(scope.row.id,scope.row.state)"
                  :width="30" style="margin-left:5px">
                </el-switch>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div class="insp-page">
        <el-pagination background layout="prev, pager, next" :current-page.sync="currentPage"
          :hide-on-single-page="false" @current-change="handlePageChange" :page-size="pageSize" :total="recordsTotal">
        </el-pagination>
      </div>

    </div>

    <!--新增/编辑计划-->
    <vx-popup :title="dialogTitle" width="1000px" @close="cancelSubmit" :active.sync="dialogVisible"
      @confirmPopup="handleSubmit" @cancelPopup="cancelSubmit" clearable>
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" class="demo-ruleForm">
        <div>
          <el-row justify="space-between" :gutter="20">
            <el-col :span="12">
              <el-form-item label="计划名称 :" prop="name" label-width="95px">
                <el-input v-model="ruleForm.name" placeholder="请输入计划名称" size="small" style="width:100%" clearable>
                </el-input>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="养护桥梁 :" prop="bridge" label-width="95px">
                <el-select filterable v-model="ruleForm.bridge" placeholder="请选择养护桥梁" size="small" style="width:100%"
                  @change="(event)=>handleBridgeChange(event)" clearable value-key="id">
                  <el-option v-for="item in bridgeOptions" :key="item.id" :label="item.name" :value="item">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row justify="space-between" :gutter="20">
            <el-col :span="12">
              <el-form-item label="养护对象 :" prop="maintenanceObject" label-width="95px">
                <el-cascader v-model="ruleForm.maintenanceObject" :options="deasePosOptions" :key="isResouceShow"
                  :props="{label:'name',value:'id',children:'children'}" size="small" style="width:100%"
                  placeholder="请选择养护对象">
                </el-cascader>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="创建依据 :" prop="maintenanceNorm" label-width="95px">
                <el-select v-model="ruleForm.maintenanceNorm" placeholder="请选择创建依据" size="small" style="width:100%"
                  clearable>
                  <el-option label="城市养护规范" :value="0"></el-option>
                  <el-option label="公路养护规范" :value="1"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row justify="space-between" :gutter="20">
            <el-col :span="12">
              <el-form-item label="养护周期 :" prop="cycle" label-width="95px">
                <el-select v-model="ruleForm.cycle" placeholder="请选择养护周期" size="small" style="width:100%" clearable>
                  <el-option label="月" :value="0"></el-option>
                  <el-option label="日" :value="1"></el-option>
                  <el-option label="周" :value="3"></el-option>
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="养护频次 :" prop="frequency" label-width="95px">
                <el-input type="number" v-model="ruleForm.frequency" placeholder="请输入养护频次" size="small"
                  style="width:100%" clearable>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row justify="space-between" :gutter="20">
            <el-col :span="12">
              <el-form-item label="执行区间 :" prop="execTime" label-width="95px">
                <el-date-picker value-format="yyyy-MM-dd HH:mm:ss" format="yyyy-MM-dd HH:mm:ss"
                  :default-time="['12:00:00']" style="width:100%" v-model="ruleForm.execTime" type="datetimerange"
                  size="small" range-separator="——" start-placeholder="开始时间" end-placeholder="结束时间" clearable>
                </el-date-picker>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="有效区间 :" prop="validTime" label-width="95px">
                <el-date-picker value-format="yyyy-MM-dd HH:mm:ss" format="yyyy-MM-dd HH:mm:ss"
                  :default-time="['12:00:00']" style="width:100%" v-model="ruleForm.validTime" type="datetimerange"
                  size="small" range-separator="——" start-placeholder="开始时间" end-placeholder="结束时间" clearable>
                </el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row justify="space-between" :gutter="20">
            <el-col :span="12">
              <el-form-item label="开始时间 :" prop="planStartTime" label-width="95px">
                <el-date-picker value-format="yyyy-MM-dd HH:mm:ss" format="yyyy-MM-dd HH:mm:ss" style="width:100%"
                  v-model="ruleForm.planStartTime" type="datetime" size="small" placeholder="选择计划开始时间" clearable>
                </el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row justify="space-between" :gutter="20">
            <el-col :span="24">
              <el-form-item label="养护内容 :" prop="maintenanceDescribe" label-width="95px">
                <el-input type="textarea" maxlength="200" rows="4" v-model="ruleForm.maintenanceDescribe"
                  style="width:100%" show-word-limit>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </el-form>
    </vx-popup>
  </div>
</template>
<script>
  import axios from "@/http/axios";
  import base from "@/api/base";
  export default {
    data() {
      return {
        isResouceShow: 0,
        curingPlanName: "",
        pageSize: 14,
        currentPage: 1,
        recordsTotal: 0,
        tableData: [],
        dialogVisible: false,
        dialogTitle: '',
        editId: null,
        deasePosOptions: [],
        bridgeOptions: [],
        ruleForm: {
          name: '',
          bridge: '',
          maintenanceObject: [],
          maintenanceDescribe: '',
          maintenanceNorm: '',
          cycle: '',
          frequency: '',
          execTime: [],
          validTime: [],
          planStartTime: ''
        },
        rules: {
          name: [{
            required: true,
            message: "请输入计划名称",
            trigger: "blur"
          }],
          bridge: [{
            required: true,
            message: "请选择养护桥梁",
            trigger: "change"
          }],
          type: [{
            required: true,
            message: "请选择养护类型",
            trigger: "change"
          }],
          maintenanceObject: [{
            required: true,
            message: "请选择养护对象",
            trigger: "change"
          }],
          maintenanceDescribe: [{
            required: true,
            message: "请输入养护内容",
            trigger: "blur"
          }],
          maintenanceNorm: [{
            required: true,
            message: "请选择创建依据",
            trigger: "change"
          }],
          cycle: [{
            required: true,
            message: "请选择养护周期",
            trigger: "change"
          }],
          frequency: [{
            required: true,
            message: "请选择养护频次",
            trigger: "blur"
          }],
          execTime: [{
            required: true,
            message: "请选择执行区间",
            trigger: "change"
          }],
          validTime: [{
            required: true,
            message: "请选择有效区间",
            trigger: "change"
          }],
          planStartTime: [{
            required: true,
            message: "请选择计划开始时间",
            trigger: "change"
          }]
        },
      };
    },
    created() {
      this.queryBridgeList();
      this.queryForPage(1);
    },
    methods: {
      emptyForm() {
        this.$refs["ruleForm"].resetFields();
        const emptyObj = {
          name: '',
          bridge: '',
          maintenanceObject: '',
          maintenanceDescribe: '',
          maintenanceNorm: '',
          cycle: '',
          frequency: '',
          execTime: [],
          validTime: [],
          planStartTime: ''
        }
        this.ruleForm = emptyObj;
      },
      handleAdd() {
        this.emptyForm();
        this.editId = null;
        this.dialogTitle = "新增养护计划";
        this.dialogVisible = true;
      },
      queryBridgeList() {
        this.$api.bridge.AllTheBridges().then(response => {
          if (response.data.success) {
            this.bridgeOptions = response.data.data[0];
          }
        });
      },
      queryForPage(pageIndex) {
        if (pageIndex && pageIndex === 1) {
          this.currentPage = 1;
        }
        const _params = {
          pageSize: this.pageSize,
          pageNum: this.currentPage,
          name: this.curingPlanName
        }
        this.$api.curing.queryPlansPage(_params).then(response => {
          if (response.data.success) {
            if (response.data.data && response.data.data.length > 0) {
              this.tableData = response.data.data.map((item, index) => ({
                ...item,
                intervalTime: [item.intervalStartTime, item.intervalEndTime],
                validTime: [item.validStartTime, item.validEndTime],
                cycle: item.cycle === 0 ? '日' : item.cycle === 1 ? '周' : item
                  .cycle === 2 ? '月' : '',
                switch: item.state ? true : false

              }));
            } else {
              this.tableData = [];
            }
            this.recordsTotal = response.data.recordsTotal;
          }
        });
      },
      handlePageChange(currentPage) {
        this.currentPage = currentPage;
        this.queryForPage();
      },
      handleChangeStatus(val, _state) {
        this.$confirm(`是否${_state?`关闭`:`开启`}?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$api.curing.setPlanStatus({
            id: val,
            state: _state ? 0 : 1
          }).then(response => {
            if (response.data.success) {
              this.$vs.notify({
                text: '操作成功',
                color: "success",
                icon: "success"
              });
              this.queryForPage();
            } else {
              this.$vs.notify({
                text: "操作失败",
                color: "danger"
              });
              this.queryForPage();
            }
          })
        }).catch(() => {
          this.$vs.notify({
            text: "已取消操作",
            color: "primary"
          });
          this.queryForPage();
        });

      },
      handleEdit(val) {
        this.$refs["ruleForm"].resetFields();
        this.dialogTitle = '编辑养护计划';
        this.dialogVisible = true;
        this.editId = val;
        this.queryPlanById(val);
      },
      handelDelete(val) {
        this.$confirm('此操作将永久删除, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$api.curing.deletePlan([val]).then(response => {
            if (response.data.success) {
              this.$vs.notify({
                text: '删除成功',
                color: "success",
                icon: "success"
              });
              let maxPage = Math.ceil((this.recordsTotal - 1) / this.pageSize);
              if (this.currentPage > maxPage) {
                this.currentPage = maxPage
              }
              this.handlePageChange(this.currentPage);
            } else {
              this.$vs.notify({
                text: "删除失败",
                color: "danger"
              })
            }
          })
        }).catch(() => {
          this.$vs.notify({
            text: "已取消删除",
            color: "primary"
          })
        });
      },
      queryPlanById(val) {
        // console.log(val);
        this.$api.curing.queryPlanById({
          id: val
        }).then(response => {
          const _data = response.data.data;

          let _ruleForm = {
            name: _data.name,
            bridge: {
              id: _data.bridgeId,
              name: _data.bridgeName,
              bridgeTypeId: _data.bridgeTypeId
            },
            maintenanceObject: _data.maintenanceObject.split(';'),
            maintenanceDescribe: _data.maintenanceDescribe,
            maintenanceNorm: _data.maintenanceNorm,
            cycle: _data.cycle,
            frequency: parseInt(_data.frequency),
            validTime: [_data.validStartTime, _data.validEndTime],
            execTime: [_data.intervalStartTime, _data.intervalEndTime],
            planStartTime: _data.planStartTime
          }
          this.ruleForm = _ruleForm;
          this.handleBridgeChange(_ruleForm.bridge);
        });
      },
      handleSubmit() {
        this.$refs.ruleForm.validate(async (valid) => {
          if (!valid) {
            return false;
          }
          let _userInfo = JSON.parse(localStorage.getItem("userInfo"));
          let _params = {
            createUserId: _userInfo['userid']||'',
            createUserName: _userInfo['realname']||'',
            name: this.ruleForm.name,
            bridgeId: this.ruleForm.bridge['id'],
            bridgeName: this.ruleForm.bridge['name'],
            bridgeTypeId: this.ruleForm.bridge['bridgeTypeId'],
            maintenanceObject: this.ruleForm.maintenanceObject.join(';'),
            maintenanceDescribe: this.ruleForm.maintenanceDescribe,
            maintenanceNorm: this.ruleForm.maintenanceNorm,
            cycle: this.ruleForm.cycle,
            frequency: parseInt(this.ruleForm.frequency),
            intervalStartTime: this.ruleForm.execTime[0],
            intervalEndTime: this.ruleForm.execTime[1],
            validStartTime: this.ruleForm.validTime[0],
            validEndTime: this.ruleForm.validTime[1],
            planStartTime: this.ruleForm.planStartTime
          };
          // console.log(_params);
          if (this.editId) {
            _params.id = this.editId;
          }

          if (this.editId) {
            this.$api.curing.updatePlan(_params).then(response => {
              if (response.data.success) {
                this.$vs.notify({
                  text: '修改成功',
                  color: "success",
                  icon: "success"
                });
                this.dialogVisible = false;
                this.queryForPage(1);
              }
            });
          } else {
            this.$api.curing.addPlan(_params).then(response => {
              if (response.data.success) {
                this.$vs.notify({
                  text: '新增成功',
                  color: "success",
                  icon: "success"
                });
                this.dialogVisible = false;
                this.queryForPage(1);
              }
            });
          }
        });
      },
      cancelSubmit() {
        this.dialogVisible = false;
      },
      handleBridgeChange(event) {
        const _params = {
          bridgeTypeId: event['bridgeTypeId'] || '',
          pId: '-1',
          bridgeId: event['id'] || ''
        };
        this.queryConstructionModelTreeById(_params);
      },
      deepDeasePosOptions(data) {
        let _arr = [];
        let _obj = {};
        data.forEach(item => {
          const _tmp = {
            ...item
          };
          if (_tmp.children && _tmp.children.length > 0) {
            _tmp.children = this.deepDeasePosOptions(_tmp.children);
          }
          _obj = {
            id: _tmp.id,
            name: _tmp.name,
            value: `${_tmp.id};${_tmp.name}`,
          }
          if (_tmp.children && _tmp.children.length > 0) {
            _obj.children = _tmp.children;
          }
          _arr.push(_obj);
        });
        return _arr;
      },
      queryConstructionModelTreeById(_params) {
        this.$api.bridge.queryConstructionModelTreeById(_params).then(response => {
          if (response.data.success) {
            ++this.isResouceShow;
            this.deasePosOptions = response.data.data.children;
          }
        });
      },
      statusClass(type) {
        switch (type) {
          case 0:
            return "planStatusD";
          case 1:
            return "planStatusA";
          default:
            return '';
        }
      },
      statusText(type) {
        switch (type) {
          case 0:
            return "未启用";
          case 1:
            return "已启用";
          default:
            return '';
        }
      },
      inspTypeClass(type) {
        switch (type) {
          case 0:
            return 'inspTypeA';
          case 1:
            return 'inspTypeB';
          case 2:
            return 'inspTypeC';
        }
      },
      inspTypeText(type) {
        switch (type) {
          case 0:
            return '日常养护';
          case 1:
            return '亮化养护';
          case 2:
            return '定期养护';
        }
      },
    },
  };

</script>
<style scoped lang="scss">
  @import '@/views/inspection/insp.scss';

  /deep/.el-table__header tr,
  /deep/.el-table__header th {
    padding: 0;
    height: 44px;
  }

  /deep/.el-table td,
  /deep/.el-table th {
    text-align: center;
    font-size: 14px;
  }

  /deep/.el-table th {
    font-weight: 500;
    color: #fff;
  }

  /deep/.el-table td {
    font-weight: 400;
    color: #444;
    padding: 0;
    height: 44px;
    line-height: 44px;
  }

  /deep/.el-table--striped .el-table__body tr.el-table__row--striped td {
    background: #f1f5fc;
  }

  .btn {
    margin-left: 20px;
  }

</style>
